<?php
namespace forpc\controllers;

use common\models\User;
use Yii;
use yii\base\InvalidParamException;
use yii\web\BadRequestHttpException;
use yii\web\Controller;
use yii\filters\VerbFilter;
use yii\filters\AccessControl;
use common\models\LoginForm;
use forpc\models\PasswordResetRequestForm;
use forpc\models\ResetPasswordForm;
use forpc\models\SignupForm;
use forpc\models\ContactForm;
use yii\helpers\Url;

/**
 * Site controller
 */
class LoginController extends Controller{

    public $enableCsrfValidation = false;

    public function actionLogin(){
        return $this->renderPartial('login');
    }

    public function actionAsyncLogin(){
        $username = isset($_POST["username"]) ? addslashes($_POST["username"]) : "";
        $password = isset($_POST["password"]) ? addslashes($_POST["password"]) : "";

        $rememberMe = true;


        $user = User::findByUsername($username);

        if(empty($user)){
            exit(json_encode(["code"=>-1, "info"=>"用户不存在"], JSON_UNESCAPED_UNICODE));
        }

        if(md5($password) != $user["password"]){
            exit(json_encode(["code"=>-2, "info"=>"密码错误!"], JSON_UNESCAPED_UNICODE));
        }

        if(Yii::$app->user->login($user, $rememberMe ? 3600*24*30 : 0)){
            exit(json_encode(["code"=>1, "info"=>"login success!"], JSON_UNESCAPED_UNICODE));
        }else{
            exit(json_encode(["code"=>3, "info"=>"login field!"], JSON_UNESCAPED_UNICODE));
        }

    }

    /**
     * {@inheritdoc}
     */
    public function actionLogout(){
        Yii::$app->user->logout();
        $this->redirect(Url::to(["/login/login"]));
    }

}
